<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 新增角色 -->
      <el-row :gutter="20">
        <el-col :span="4">
          <el-button type="primary" @click="addRoleDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表 -->
      <el-row>
        <el-table :data="roles" stripe border>
          <!-- 展开列 -->
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-row
                :class="['bdbottom', 'vertical-center', {'bdtop':index1 === 0}]"
                v-for="(menu1,index1) in scope.row.children"
                :key="menu1.id"
              >
                <!-- 一级权限列 -->
                <el-col :span="5">
                  <el-tag closable @close="removeRightById(scope.row,menu1.id)">{{menu1.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 二级和三级权限列 -->
                <el-col :span="19">
                  <el-row
                    :class="['vertical-center', {'bdtop':index2 !== 0}]"
                    v-for="(menu2,index2) in menu1.children"
                    :key="menu2.id"
                  >
                    <el-col :span="6">
                      <el-tag
                        type="success"
                        closable
                        @close="removeRightById(scope.row,menu2.id)"
                      >{{menu2.authName}}</el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <el-col :span="18">
                      <el-tag
                        type="warning"
                        closable
                        v-for="menu3 in menu2.children"
                        :key="menu3.id"
                        @close="removeRightById(scope.row,menu3.id)"
                      >{{menu3.authName}}</el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <!-- 索引列 -->
          <el-table-column type="index"></el-table-column>
          <el-table-column prop="roleName" label="角色名称"></el-table-column>
          <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showEditPanel(scope.row.id)"
              >编辑</el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="showDeleteConfirm(scope.row.id)"
              >删除</el-button>
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showSetRightDialog(scope.row)"
              >分配权限</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
    </el-card>
    <!-- 添加新角色弹出面板 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRoleDialogVisible"
      width="50%"
      @close="addRoleDialogClosed"
    >
      <!-- 对话框主体区域 -->
      <el-form :model="addForm" :rules="roleRules" ref="addFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色信息弹出面板 -->
    <el-dialog
      title="修改角色信息"
      :visible.sync="editRoleDialogVisible"
      width="50%"
      @close="editRoleDialogClosed"
    >
      <!-- 对话框主体区域 -->
      <el-form :model="editForm" :rules="roleRules" ref="editFormRef" label-width="100px">
        <el-form-item label="ID" prop="roleId">
          <el-input v-model="editForm.roleId" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色权限弹出面板 -->
    <el-dialog
      title="分配角色权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
      <!-- 树形组件
        show-checkbox:显示复选框
        node-key:设置选中节点对应的值
        default-expand-all:是否默认展开所有节点
        :default-checked-keys 设置默认选中项的数组
      ref:设置引用-->
      <el-tree
        :data="rights"
        :props="treeProps"
        node-key="id"
        show-checkbox
        default-expand-all
        :default-checked-keys="defaultKeys"
        ref="treeRef"
      ></el-tree>
      <!-- 对话框底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roles: [],
      addRoleDialogVisible: false,
      addForm: {},
      editRoleDialogVisible: false,
      editForm: {},
      roleRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "角色名在3~10个字符之间",
            trigger: "blur"
          }
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "用户名在3~15个字符之间",
            trigger: "blur"
          }
        ]
      },
      setRightDialogVisible: false,
      // 权限树数据
      rights: [],
      // 权限树绑定属性名
      treeProps: {
        label: "authName",
        children: "children"
      },
      // 正在操作的角色所拥有的权限列表
      defaultKeys: [],
      // 正在操作的角色id
      roleId: ""
    };
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败");
      }
      this.roles = res.data;
    },
    // 获取所有权限的树状数据
    async getRightsList() {
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200) {
        return this.$message.error("获取权限树状列表失败");
      }
      this.rights = res.data;
    },
    // 弹出删除角色确认框
    async showDeleteConfirm(id) {
      this.$confirm("此操作将永久删除此角色，是否确认？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deleteRole(id);
        })
        .catch(() => {
          this.$message.info("操作已取消");
        });
    },
    // 根据id删除角色
    async deleteRole(id) {
      const { data: res } = await this.$http.delete("roles/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("删除角色失败");
      }
      this.$message.success("删除角色成功");
      this.getRolesList();
    },
    // 添加角色
    addRole() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.post("roles", this.addForm);
        if (res.meta.status !== 201) {
          return this.$message.error("添加角色失败");
        }
        this.addRoleDialogVisible = false;
        this.$message.success("添加角色成功");
        this.getRolesList();
      });
    },
    // 添加角色面板关闭事件
    addRoleDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    async showEditPanel(id) {
      const { data: res } = await this.$http.get("roles/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色信息失败");
      }
      this.editForm = res.data;
      this.editRoleDialogVisible = true;
    },
    // 提交对角色信息的修改
    editRole() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          "roles/" + this.editForm.roleId,
          this.editForm
        );
        if (res.meta.status !== 200) {
          return this.$message.error("修改角色信息失败");
        }
        this.editRoleDialogVisible = false;
        this.$message.success("修改角色信息成功");
        this.getRolesList();
      });
    },
    // 关闭修改角色信息面板事件
    editRoleDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    // 根据id，从指定角色中移除权限
    removeRightById(role, rightId) {
      this.$confirm("此操作将永久删除此权限且不可恢复，是否确认", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/${role.id}/rights/${rightId}`
          );
          if (res.meta.status !== 200) {
            return this.$message.error("删除角色权限失败");
          }
          this.$message.success("删除角色权限成功");
          role.children = res.data;
        })
        .catch(() => this.$message.info("操作已取消"));
    },
    // 弹出分配角色权限面板
    async showSetRightDialog(role) {
      this.roleId = role.id;

      // 重新获取所有权限
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200) {
        return this.$message.error("获取权限树状列表失败");
      }
      this.rights = res.data;

      // 获取当前角色所拥有的三级权限id列表
      this.getLeafKeys(role, this.defaultKeys);
      this.setRightDialogVisible = true;
    },
    //  关闭分配角色权限面板事件
    setRightDialogClosed() {
      this.defaultKeys = [];
    },
    // 递归查找某权限节点下所有的三级权限节点
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach(child => this.getLeafKeys(child, arr));
    },
    async allotRights() {
      const keys = [
        this.$refs.treeRef.getCheckedKeys(),
        this.$refs.treeRef.getHalfCheckedKeys()
      ];
      const idString = keys.join(",");
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        {
          rids: idString
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("角色授权失败");
      }
      this.$message.success("角色授权成功");
      this.setRightDialogVisible = false;
      this.getRolesList();
    }
  },
  created() {
    this.getRolesList();
    this.getRightsList();
  }
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 8px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vertical-center {
  display: flex;
  align-items: center;
}
</style>
